<?php

namespace nz\co\gravitate\FTAWebServices;
		
		define ("FTA_CURL_NORESPONSE",-1);
		
        class FTACurlPost { 
				
				// extends FTAObject {
				var $host;
				var $port;
				var $endPoint;
				var $httpVersion;
				
				var $compress;
				var $keepAlive;
				var $verifyCertificates;

				var $id;
				
				var $curlHandler;
				
				var $debug;
				
				var $errorNo;
				var $errorMessage;
				
				var $proxy;
				var $proxyPort;
				
                function __construct($host, $port=80, $endPoint, $proxy=null, $proxyPort = '8888') {
	
					$this->host = $host;
					$this->port = $port;
					$this->endPoint = $endPoint;
					
					$this->httpVersion = "1.1";

					$this->keepAlive = false;
					$this->compress = false;
					$this->verifyCertificates = false;
					$this->debug = false;
					
					$this->errorNo  = 0;
					$this->errorMessage  = null;
					$this->proxy = $proxy;
					$this->proxyPort = $proxyPort;
					
                }

		
			
			
			// simple method for processing json delivery..
			// not as fully functioned as the xmlrpc based stuff.
			// but does the encoding proper.. we can always extend the class if
			// we need to.. or add hooks like the other fta extension mechanisims..
			function deliverPayload($payload,$contentType='text/plain'){
				
				$this->errorNo = 0;
				$this->errorMessage = null;
							
				if(is_null($this->curlHandler)){
					
					$u = $this->host . ':' . $this->port . $this->endPoint ;
					
					if ($this->debug)
						echo "endpoint url: " . $u . "<br/>";
						
					$this->curlHandler = curl_init($u);
				}			
			
				curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER, 1);			
				curl_setopt($this->curlHandler, CURLOPT_POST, 1);
				curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS, $payload);
				
				if (!is_null($this->proxy)){
					curl_setopt($this->curlHandler, CURLOPT_PROXY, $this->proxy);
					curl_setopt($this->curlHandler, CURLOPT_PROXYPORT, $this->proxyPort);
					
				}
				
				//set the content type
				curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER,array('Content-Type: ' . $contentType)); 
				
			// dont really care about headers, will try and process everything.. 
			//	curl_setopt($this->curlHandler, CURLOPT_HEADER, 1);
				
				
				if($this->debug) {
					curl_setopt($this->curlHandler, CURLOPT_VERBOSE, 1);
				}
				
				$result = curl_exec($this->curlHandler);
				
				//after the invocation.. clean up.. if keep alive is false..  or we have an error
				if (!$this->keepAlive || !$result){
					curl_close($this->curlHandler);
					$this->curlHandler = null;
					//error situation..
					if (is_null($result)){
						$this->errorNo = FTA_CURL_NORESPONSE;// should be numeric..
						$result = null;
						return null;
					}
				}
				
				
				return $result;
			}
			
			
			
			//add destructor..
			
        }

